// 以下已通过自动引入配置，无需手动导入：
// defineStore, ref, computed, debounce

export const useAppStore = defineStore('app', () => {
  // 状态
  const loading = ref(false)
  const collapsed = ref(false)
  const theme = ref(localStorage.getItem('theme') || 'light')
  const lang = ref(localStorage.getItem('lang') || 'zh-CN')
  const breadcrumbs = ref([])
  const cachedViews = ref([]) // 缓存的视图组件

  // 计算属性
  const isDark = computed(() => theme.value === 'dark')
  const isCollapsed = computed(() => collapsed.value)

  // 操作
  const setLoading = value => {
    loading.value = value
  }

  const toggleCollapsed = () => {
    collapsed.value = !collapsed.value
  }

  const setCollapsed = value => {
    collapsed.value = value
  }

  const setTheme = newTheme => {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)

    // 更新HTML根元素的class
    const html = document.documentElement
    if (newTheme === 'dark') {
      html.classList.add('dark')
    } else {
      html.classList.remove('dark')
    }
  }

  const setLang = newLang => {
    lang.value = newLang
    localStorage.setItem('lang', newLang)
  }

  const setBreadcrumbs = crumbs => {
    breadcrumbs.value = crumbs
  }

  // 缓存视图相关操作
  const addCachedView = viewName => {
    if (!cachedViews.value.includes(viewName)) {
      cachedViews.value.push(viewName)
    }
  }

  const removeCachedView = viewName => {
    const index = cachedViews.value.indexOf(viewName)
    if (index > -1) {
      cachedViews.value.splice(index, 1)
    }
  }

  const clearCachedViews = () => {
    cachedViews.value = []
  }

  // 防抖的loading设置函数
  const debouncedSetLoading = debounce(value => {
    loading.value = value
  }, 100)

  // 全局错误处理
  const handleError = (error, context = '') => {
    console.error(`[${context}] Error:`, error)
    // 这里可以添加错误日志上报逻辑
  }

  // 初始化主题
  const initTheme = () => {
    setTheme(theme.value)
  }

  return {
    // 状态
    loading,
    collapsed,
    theme,
    lang,
    breadcrumbs,
    cachedViews,
    // 计算属性
    isDark,
    isCollapsed,
    // 操作
    setLoading,
    toggleCollapsed,
    setCollapsed,
    setTheme,
    setLang,
    setBreadcrumbs,
    addCachedView,
    removeCachedView,
    clearCachedViews,
    debouncedSetLoading,
    handleError,
    initTheme
  }
})
